package com.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

import static com.util.Constant.USERNAME;

//@WebFilter("/*")
public class RememberFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI();
        if (!requestURI.startsWith("/https:/")) {
            String  username =(String) session.getAttribute(USERNAME);
            if(Objects.nonNull(username)){//说明已经登录过了，并且session有了
                filterChain.doFilter(servletRequest, servletResponse);
            }else {
                Cookie[] cookies = request.getCookies();
                if(Objects.nonNull(cookies)){
                    Arrays.stream(cookies).filter(cookie -> cookie.getName().equals(USERNAME))
                            .findFirst().ifPresentOrElse(
                                    cookie -> {
                                        request.getSession().setAttribute("username",cookie.getValue());
                                        try {
                                            filterChain.doFilter(servletRequest, servletResponse);
                                        } catch (IOException | ServletException e) {
                                            throw new RuntimeException(e);
                                        }
                                    },
                                    ()->{
                                        try {
                                            servletRequest.getRequestDispatcher("/adminLogin").forward(servletRequest,servletResponse);
                                        } catch (ServletException | IOException e) {
                                            throw new RuntimeException(e);
                                        }
                                    });
                }else {
                    servletRequest.getRequestDispatcher("/adminLogin").forward(servletRequest,servletResponse);
                }

            }
        }

    }
}
